package com.lei.baweiliao.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.lei.baweiliao.R;
import com.lei.baweiliao.threadhelper.ThreadHelper;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText reg_username;
    private EditText reg_pwd;
    private Button reg_bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        reg_username = (EditText) findViewById(R.id.reg_username);
        reg_pwd = (EditText) findViewById(R.id.reg_pwd);
        reg_bt = (Button) findViewById(R.id.reg_bt);

        reg_bt.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reg_bt:
                submit();
                //注册失败会抛出HyphenateException
                ThreadHelper.getInstance().getExecutors().submit(() -> {
                    try {
                        EMClient.getInstance().createAccount(reg_username.getText().toString().trim(), reg_pwd.getText().toString().trim());//同步方法
                        runOnUiThread(() ->
                                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show()
                        );
                        startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
                        finish();
                    } catch (HyphenateException e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(this, "" + e.getDescription(), Toast.LENGTH_SHORT).show());
                    }
                });
                break;
        }
    }

    private void submit() {
        // validate
        String username = reg_username.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入要注册的用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        String pwd = reg_pwd.getText().toString().trim();
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "请输入要注册的密码", Toast.LENGTH_SHORT).show();
            return;
        }

        // TODO validate success, do something


    }
}
